﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using EdexClient;

namespace Edex2IbsSaleOrderLoader
{
    public partial class Service1 : ServiceBase
    {

        private Timer timer = null;
        private EdexClient.API_SESSION session = new API_SESSION();

        public Service1()
        {
            InitializeComponent();

            try
            {
                if (!EventLog.SourceExists(this.ServiceName + "_log"))
                    EventLog.CreateEventSource(this.ServiceName, this.ServiceName + "_log");
            }
            catch { }

            serviceLog.Source = this.ServiceName + "_log";
            serviceLog.Log = this.ServiceName + "_log";

        }

        protected override void OnStart(string[] args)
        {
            serviceLog.WriteEntry(this.ServiceName + " запущен");

            Properties.Settings.Default.Reload();            

            var ExecuteTimes = Properties.Settings.Default.ExecuteTimes;

            if (Properties.Settings.Default.ExecuteImmediately)
                ExecuteTimes.Add(DateTime.Now.AddMinutes(1).ToString("HH:mm"));

            timer = new Timer();
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = TimerUtil.GetNewTimerInterval(ExecuteTimes);
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            serviceLog.WriteEntry(this.ServiceName + " остановлен");

            timer.Stop();
            timer.Close();
        }

        /// <summary>
        /// При срабатывании таймера
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            // Останавливаем таймей и стартуем выполнение выгрузки
            timer.Stop();

            Process();

            // Интервал таймера
            Properties.Settings.Default.Reload();
            timer.Interval = TimerUtil.GetNewTimerInterval(Properties.Settings.Default.ExecuteTimes);
            timer.Start();
        }

        private void Process()
        {
            try
            {
                serviceLog.WriteEntry("Запуск процедуры");
                Properties.Settings.Default.Reload();

                string connectionString = Properties.Settings.Default.IBSConnectionString;
                string api = Properties.Settings.Default.ApiSite;
                string serviceMailAddress = Properties.Settings.Default.ServiceMailAddress;
                string userMailAddress = Properties.Settings.Default.UserMailAddress;
                
                var ibs = new IBS.IbsDataContext(connectionString);
                var edex = new EdexClient.EdexContext(api);
                var login = Properties.Settings.Default.apiLogin;
                var pass = Properties.Settings.Default.apiPass;

                try
                {
                    serviceLog.WriteEntry("Загрузка накладных ТНК...");
                    session = edex.GetSession(login, pass);
                    edex.ChangeCompany("d2a07f89-f38e-46cb-bec8-dc38b4e8d8cb", session.APIKEY); //TNK   
                    session = edex.GetSession(login, pass);
                    var tnkSaleOrders = edex.GetIncomingInvoicesCommerceML(session.APIKEY);
                    new CommerceML2IBS
                        .IntegrationContext(connectionString)
                        .Process(tnkSaleOrders);
                    serviceLog.WriteEntry("Загрузка накладных BP...");
                    edex.ChangeCompany("E4EFEE0D-0162-4FE8-B3A8-22DFFDDBA32B", session.APIKEY); //PETROL
                    session = edex.GetSession(login, pass);
                    var bpSaleOrders = edex.GetIncomingInvoicesCommerceML(session.APIKEY);
                    new CommerceML2IBS
                        .IntegrationContext(connectionString)
                        .Process(bpSaleOrders);
                }
                catch (Exception ex)
                {
                    string errMsg = "При выполнении загрузки накладных произошла ошибка: " + ex.Message + "\n" + ex.StackTrace;
                    serviceLog.WriteEntry(errMsg, EventLogEntryType.Error);
                    ibs.SendMail(serviceMailAddress, userMailAddress, "Ошибка загрузки накладных EDEX", errMsg);
                }
                serviceLog.WriteEntry("Загрузка завершена");
            }
            catch (Exception ex)
            {
                string errMsg = "При выполнении процедуры произошла ошибка " + ex.Message + "\n" + ex.StackTrace;
                serviceLog.WriteEntry(errMsg, EventLogEntryType.Error);
            }
        }
    }
}
